package cn.tedu.yhg.tool;

import java.io.*;
import java.util.List;

public class GoodFieldTransferDatabase {
    /*
    废弃byte[] 是一个数组类型，而不是一个普通的类，它没有默认的无参构造方法，因此会抛出 InstantiationException 异常。
    public static <V> V serialize(Object source, Class<V> clazz) {
        V result = null;
        try {
            result = clazz.newInstance();//Class clazz传入什么类.class就是什么类.class,clazz.newInstance返回了对应类型实例,确保了result的类型
            //result = clazz.newInstance();但此时实际上result被向上造型为Object类了
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(source);
                oos.close();
                result = (V) baos.toByteArray();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return result;//返回的是Object,但clazz反射机制储存了目标结果的类型,最终,编译器会帮我我们强转如Weibo weibo = (Weibo)BeanCopyUtils.copyBean(weiboDTO, Weibo.class);
    }*/

    public static <V> V serialize(Object source, Class<V> clazz) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(source);
            oos.close();
            // 序列化后的结果是 byte[] 类型
            byte[] bytes = baos.toByteArray();
            // 检查目标类型是否是 byte[]，如果是，则直接返回
            if (clazz == byte[].class) {
                return (V) bytes;
            } else {
                throw new IllegalArgumentException("Unsupported target class: " + clazz.getName());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static  <V> List<V> deserialize(byte[] source, Class<V> clazz) {
        List<V> result = null;
            //Class clazz传入什么类.class就是什么类.class,clazz.newInstance返回了对应类型实例,确保了result的类型
            //result = clazz.newInstance();但此时实际上result被向上造型为Object类了
            try {
                ByteArrayInputStream bais = new ByteArrayInputStream(source);
                ObjectInputStream ois = new ObjectInputStream(bais);
                try {
                    result = (List<V>) ois.readObject();
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
                ois.close();

            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        return result;//返回的是Object,但clazz反射机制储存了目标结果的类型,最终,编译器会帮我我们强转如Weibo weibo = (Weibo)BeanCopyUtils.copyBean(weiboDTO, Weibo.class);
    }
}
